define(function(require, exports, module) {
    'use strict';
    var rk = require('rk');

    $.widget('rk.xsySuButtonBar', $.rk.xsyBase, {
        _params: {},
        _create: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            elem.addClass('xsy_buttonbar');
            elem.attr('is-private', 'true');

            //监听点击事件
            var ownerData = me._getOwnerData();
            if (!ownerData) return;
            var toolBarData = me._getOwnerData().toolBarData;

            if(toolBarData){
                toolBarData = $.extend(toolBarData, opt);
            }
            elem.on('click', '[act]', function() {
                var act = $(this).attr('act');
                if(xsy.account[act]){
                    xsy.account[act](toolBarData, me.getUid(), me.getType()); //执行
                }else if(me[act]){
                    me[act](toolBarData, me.getUid(), me.getType());
                }
               
            })

            elem.on('mouseenter mouseleave', '.xsy_buttonbar_list > li', function() {
                var li = $(this),
                    more = $('a.xsy_buttonbar_link', this),
                    childmenu = $('div.xsy_buttonbar_menu1', this);
                more.toggleClass('actived');
                childmenu.toggle();
                return;
            });
            elem.on('mouseenter mouseleave', '.xsy_buttonbar_menu1 li', function() {
                var li = $(this),
                    childmenu = $('div.xsy_buttonbar_submenu', this);
                li.toggleClass('hover');
                childmenu.toggle();
                return;
            });
            $('body').on('click.xsySuButtonBar', function(e) {
                if ($(e.target).closest('.xsy_buttonbar').size() > 0) return;
                elem.find('.xsy_buttonbar_menu').hide();
            })

            me.render(opt.toolbarData);
        },

        _init: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var id = me._getDetailId();
            var belongId = me._getBelongId();

            //新建采用之前的东西，需要往按钮上面append一堆东西
            elem.find("[act^='create']").each(function(i, el) {
                var item = $(el);
                var entityId = item.attr("entity-id");

                var businessInfo = rk.queryBelong(entityId);
                var business = "";
                var businessName = "";
                if (businessInfo) {
                    //标准单据在标准单据
                    business = businessInfo.name;
                    businessName = businessInfo.label;
                    if(belongId < 999){
                        var parentInfo = rk.queryBelong(belongId);
                        var paramName = (parentInfo ? parentInfo.name : "account") + "Id";
                        item.attr('business', business);
                        item.attr('businessName', businessName);
                        item.attr("postdata", "{\"" + paramName + "\":" + id + "}")
                    }else{
                        //标准单据在自定义单据
                        item.attr('business', business);
                        item.attr('businessName', businessName);
                        item.attr('postdata', '{"relationBelongId":' + belongId + ',"relationId":' + id + ', "belongId":' + entityId + '}');
                    }
                } else {
                    item.attr('pos', 'customize');
                    item.attr('business', 'customize');
                    item.attr('postdata', '{"relationBelongId":' + belongId + ',"relationId":' + id + ', "belongId":' + entityId + '}');
                    //往按钮上面补全数据
                }
            });


            elem.find("[act^=edit]:not([act='editOppProduct'])").attr('act', 'editBusiness').each(function(i, el) {
                var item = $(el);
                var entityId = item.attr("entity-id");

                var businessInfo = rk.queryBelong(entityId);
                var commonData = me._getCommonData();
                if(businessInfo && entityId < 999){
                    var business = businessInfo.name;
                    var businessName = businessInfo.label;
                    var paramName = business + "Id";
                    item.attr('business', business);
                    item.attr('businessName', businessName);

                    item.attr('postdata', "{\"" + paramName + "\":" + id + "}"); 
                }else{
                    item.attr('business', 'customize');
                    var businessName = commonData ? commonData.belongLabel : '';
                    item.attr('businessName', businessName);
                    item.attr('postdata', "{\"customizeId\":" + id + ", \"belongId\":" + belongId + "}"); 
                }
                

            });


            elem.find("[act^='print']").each(function(index, el) {
                var item = $(el);
                var templateId = item.attr("data-id");
                item.attr('href', '/json/crm_template_print/print.action?templatePrintId=' + templateId+ '&systemItemId=' + me._getDetailId());

            });

            var triggerReload = function(entity) {
                me._triggerOuterEvent('reloadRefer', {
                    entity: entity
                });
                me._triggerOuterEvent('referDataUpdated');
            }


            $('body').editBusiness({
                getAllData: 1,
                onSuccess : function(){
                    me._triggerOuterEvent('afterPopupEdit');
                }
            }).edit_products({
                onSuccess : function(){
                    triggerReload('product');
                }
            }).newCreateOpportunity({
                onSuccess: function() {
                    triggerReload('opportunity');
                }
            }).createLead({
                onSuccess: function() {
                    triggerReload('lead');
                }
            }).newCreateAccount({
                onSuccess: function() {
                    triggerReload('account');
                }
            }).createContact({
                onSuccess: function() {
                    triggerReload('contact');
                }
            }).createContract({
                onSuccess: function() {
                    triggerReload('contract');
                }
            }).createCampaign({
                onSuccess: function() {
                    triggerReload('campaign');
                }
            }).newCreateCustomize({
                onSuccess: function() {
                    triggerReload('customize');
                }
            }).newCreateOrder({
                onSuccess: function() {
                    triggerReload('order');
                }
            }).createCase({
                onSuccess: function() {
                    triggerReload('case');
                }
            }).addCompetitor({
                onSuccess: function() {
                    triggerReload('competitor');
                }
            }).addPartner({
                onSuccess: function() {
                    triggerReload('partner');
                }
            }).addContactNew({
                onSuccess: function() {
                    triggerReload('contact');
                }
            });

            me._selfInit();
        },


        _selfInit : function(){

        },

        render: function(toolbarData) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            //渲染toolbar
            //console.log('toolbarData', toolbarData);
            var tpl = require('platform/widgets/crm/su/xsySuButtonBar/widget.tpl');
            var html = rk.templateText(tpl, {
                toolbarData: toolbarData,
                language:window.SESSION.user.language
            });
            elem.html(html).addClass('xsy_buttonbar');
        },


        viewEntityLog : function(data){
            $.postJson(data.url, data.postJson).done(function(resultData) {
                if (resultData.status == 0) {
                    $.viewEntityLog(resultData.data, 2);
                } else {
                    $.msg(rk.i18n('CRM_CORE_OPERATE') + rk.i18n('CRM_CORE_FAILED'));
                }
            }).fail(function(def, code, message) {
                $.msg(rk.i18n('REQUEST_ERROR'));
            });
        },

        deleteEntity : function(data){
            $.confirm(data.tip, function(){
                $.postJson(data.url, data.postJson).done(function(json){
                    if(json.status == 0){
                        if(data.callback){
                            data.callback();
                        }
                        $.msg(rk.i18n('CRM_CORE_DELETE') + rk.i18n('CRM_CORE_SUCCESS'), 1);
                    }else{
                        $.msg(rk.i18n('CRM_CORE_DELETE') + rk.i18n('CRM_CORE_FAILED'));
                    }
                }).fail(function(def, code, message){
                    def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
                })
            })
        },

        transferEntity : function(data){
            var name = data.name;
            var entityName = data.entityName;
            var url = data.url;
            var postJson = data.postJson;
            var callback = data.callback;

            var $dialog = $($.format($.trim(require('oldcrm/tmpl/scrpt_tmpl_transfer_entity.tpl')), {
                target: name
            }));
            var $input = $dialog.find('input[field=transferUser]');

            $dialog.popup({
                width: 520,
                title: rk.i18n('CRM_CORE_TRANSFER') + entityName,
                actions : {
                    save : function(evt, dialog){
                        var transferUserId = $input.attr('ownerId');
                        if (transferUserId) {
                            var $lnk = $(this).loading();
                            $.postJson(url, $.extend(postJson, {target : transferUserId})).done(function(json) {
                                if (json.status == 0) {
                                    dialog.close();

                                    callback && callback(json);

                                    $.msg(rk.i18n('CRM_CORE_TRANSFER')+rk.i18n('CRM_CORE_SUCCESS'), 1);
                                } else {
                                    $.msg(rk.i18n('REQUEST_ERROR'));
                                    $lnk.loading('end');
                                }
                            }).fail(function(def, code, message) {
                                $.msg(rk.i18n('REQUEST_ERROR'));
                                $lnk.loading('end');
                            });
                        } else {
                            $.msg(rk.i18n('ACCOUNT_SELECTED_TRANSFER_TO'));
                        }
                    }
                },
                create: function() {
                    $input.autocomplete({
                        minLength: 0,
                        source: function(request, response) {
                            var key = $.trim(request.term);
                            $.postJson("/json/crm_search/all-users.action", {
                                pageNo: 1,
                                key: key
                            }).done(function(data) {
                                var id;
                                if (data.length > 0) {
                                    $.each(data, function(i, d) {
                                        if (d.value == key) {
                                            id = d.id;
                                        }
                                    });
                                }
                                id ? $input.attr('ownerId', id) : $input.removeAttr('ownerId');
                                response(data);
                            });
                        },
                        select: function(event, ui) {
                            var id = ui.item.id;
                            $input.attr('ownerId', id);
                        }
                    });                        
                }
            })
        }

    });
});
